<?php

class ShiftServiceTest extends PHPUnit_Framework_TestCase{

    private $subject;

    /**
     * Prepares the environment before running a test.
     */
    protected function setUp ()
    {
        parent::setUp();
        $this->subject = new Core_Service_Shift(new Core_Gateway_Shift());
    }

    /**
     * Cleans up the environment after running a test.
     */
    protected function tearDown ()
    {
        parent::tearDown();
        unset($this->subject);
    }

    /**
     * Constructs the test case.
     */
    public function __construct ()
    {

    }
    
    public function testExtendsRedCrossServiceAbstract()
    {
    	$this->assertTrue($this->subject instanceof RedCross_Service_ServiceAbstract);
    }
    
    
    /**
     * @expectedException Doctrine_Connection_Mysql_Exception
     */
    
    public function testDoesNotInsertEmptyModel()
    {
    	$model = new Core_Model_Shift();
    	$this->subject->save($model);
    }
    
    /**
     *  @expectedException RedCross_Service_Exception
     */
    public function testFetchMembersWithCoursesFailsOnNonInt()
    {
        $thisisastring = 'this is a string';
        $this->subject->fetchMembersWithCourses($thisisastring);
    }
    
    public function testFetchMembersWithCourses()
    {
        $fetchedMembers = $this->subject->fetchMembersWithCourses(1);
        
        $testmembers = Doctrine_Query::create()
        	->select('m.id, m.first_name, m.last_name, (SELECT COUNT(*) FROM RedCross_Gateway_Base_RoleCourse rc WHERE rc.role_id = 1) AS courses')
          	->from('Core_Model_Member m')
         	->leftJoin('m.Courses c')
         	->addWhere('c.id IN (SELECT rc2.course_id FROM RedCross_Gateway_Base_RoleCourse rc2 WHERE rc2.role_id = 1)')
        	->groupBy('m.id')
        	->having('COUNT(*) = courses')
        	->fetchArray();
        
        $counter = 0;
        foreach($fetchedMembers as $row){
            $this->assertEquals($row,$testmembers[$counter]);
            $counter++;
        }
        $this->assertEquals(count($fetchedMembers), count($testmembers));
        
    }
    
    public function testAdd()
    {
        /*
         id  	bigint(20)  	 	  	No  	None  	auto_increment  	  Browse distinct values   	  Change   	  Drop   	  Primary   	  Unique   	  Index   	 Fulltext
	name 	varchar(32) 	latin1_swedish_ci 		No 			Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
	created_at 	datetime 			No 			Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
	appearance_time 	datetime 			No 			Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
	from_date 	datetime 			No 			Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
	to_date 	datetime 			No 			Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
	special_description 	varchar(255) 	latin1_swedish_ci 		Yes 	NULL 		Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
	equipment_list 	varchar(255) 	latin1_swedish_ci 		Yes 	NULL 		Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
	event_id 	bigint(20) 			No 			Browse distinct values 	Change 	Drop 	Primary 	Unique 	Index 	Fulltext
	shift_report_id 	
         
         
         1 	Test skift 	2010-03-14 23:08:15 	2010-01-01 00:00:00 	2010-01-01 00:00:00 	2010-01-01 00:00:00 	adsfkjglka 	lakdfjglkaf 	2  	
         
         $model_object = new Core_Model_Event();
	
	$model_object->name = $data['name'];
	$model_object->description = $data['description'];
	$model_object->location = $data['location'];
	$model_object->contact_name = $data['contact_name'];
	$model_object->contact_phone = $data['contact_phone'];
	$model_object->from_date = $data['from_date'];
	$model_object->to_date = $data['to_date'];
	$model_object->requested_resource = $data['requested_resource'];
	$model_object->is_active = $data['is_active'];
	$model_object->member_id = $data['member_id'];
	$model_object->created_at = $data['created_at'];
         
        */
        $data = array(
            'name' => 'Test Shift',
            'created_at' => '2010-03-14 23:08:15',
            'appearance_time' => '2010-03-14 23:08:15',
            'from_date' => '2010-03-14 23:08:15',
            'to_date' => '2010-03-14 23:08:15',
            'special_description' => 'test description',
            'equipment_list' => 'equipment bla bla bla',
            'event_id' => 1,
            'shift_report_id' => 1
        );
        
        $model_object = new Core_model_Shift();
        
        $model_object->name = $data['name'];
        $model_object->created_at = $data['created_at'];
        $model_object->appearance_time = $data['appearance_time'];
        $model_object->from_date = $data['from_date'];
        $model_object->to_date = $data['to_date'];
        $model_object->special_description = $data['special_description'];
        $model_object->equipment_list = $data['equipment_list'];
        $model_object->event_id = $data['event_id'];
        $model_object->shift_report_id = $data['shift_report_id'];
                       
        $this->assertEquals($model_object->name, $data['name']);
        $this->assertEquals($model_object->created_at, $data['created_at']);
        $this->assertEquals($model_object->appearance_time, $data['appearance_time']);
        $this->assertEquals($model_object->from_date, $data['from_date']);
        $this->assertEquals($model_object->to_date, $data['to_date']);
        $this->assertEquals($model_object->special_description, $data['special_description']);
        $this->assertEquals($model_object->equipment_list, $data['equipment_list']);
        $this->assertEquals($model_object->event_id, $data['event_id']);
        $this->assertEquals($model_object->shift_report_id, $data['shift_report_id']);
        
        $this->subject->add($model_object);
        
        $fetched_model = $this->subject->fetch((int)$model_object->id);
        
        $this->assertTrue(is_object($fetched_model));
        
        $this->assertEquals($model_object->name, $fetched_model->name);
        $this->assertEquals($model_object->created_at, $fetched_model->created_at);
        $this->assertEquals($model_object->appearance_time, $fetched_model->appearance_time);
        $this->assertEquals($model_object->from_date, $fetched_model->from_date);
        $this->assertEquals($model_object->to_date, $fetched_model->to_date);
        $this->assertEquals($model_object->special_description, $fetched_model->special_description);
        $this->assertEquals($model_object->equipment_list, $fetched_model->equipment_list);
        $this->assertEquals($model_object->event_id, $fetched_model->event_id);
        $this->assertEquals($model_object->shift_report_id, $fetched_model->shift_report_id);
        
    }
    
    public function testFetchAllActive()
    {
        $temp = Doctrine_Query::create()
			->select('s.id, s.name, s.from_date')
			->from('Core_Model_Shift s')
			->leftJoin('s.Event e')
			->where('e.is_active = 1')
			->fetchArray();
                        
        $count = count($temp);
        
        $allactiveShifts = $this->subject->fetchAllActive();
        $fetchedCount = count($allactiveShifts);
        
        $this->assertEquals($count, $fetchedCount);
        
        $this->assertEquals($temp, $allactiveShifts);
    
    }
    
/*

			FUCK
			
			THIS
			
			SHIT

    public function testFetchAllVisibleForMemberWithoutFilterData()
    {
    	//Lag et shift. Assert at fetchAllVisible returnerer false
    	//Lag en notification. Sett member id. Ikke sett sent_date. AssertFalse
    	//Sett sent_date. Assert at det returnerer 1
    	//Lag nytt shift med utsendt notification. Assert at returenrerer 2
    	$date = new Zend_Date();
    	$member = $this->_getAndSaveMember();
    	$shift = $this->_getAndSaveShiftWithRoles(); //array('count' => 1, 'member_id' => $member->id)
    	$this->assertEquals(0,count($this->subject->fetchAllVisibleForMember($member->id)));
    	$shift->Roles[]->member_id = $member->id;
    	$this->subject->save($shift);
    	$this->assertEquals(0,count($this->subject->fetchAllVisibleForMember($member->id)));
    	$shift->Roles[0]->notification_sent_time = $date->get('YYYY-MM-dd HH:mm:ss');
    	$this->subject->save($shift);
    	$this->assertEquals(1,count($this->subject->fetchAllVisibleForMember($member->id)));
    	
    }
    
    private function _getAndSaveShiftWithRoles(array $rolesInfo = null)
    {
		$event = $this->_getAndSaveEvent();
    	$shift = new Core_Model_Shift();
    	$shift->Event = $event;
    	$shift->name = 'autogenerated test shift';
    	if (!is_null($rolesInfo))
    	{
    		for ($i = 0; $i < $rolesInfo['count']; $i++)
    		{
    			$shift->Roles[] = new Core_Model_ShiftRole();
    			if (array_key_exists('member_id',$rolesInfo))
    			{
    				$shift->Roles[$i]->member_id = 
    					is_array($rolesInfo['member_id']) ? 
    					$rolesInfo['member_id'][$i] : 
    					$rolesInfo['member_id'];
    			}
    			if (array_key_exists('notification_sent_time',$rolesInfo))
    			{
    				$shift->Roles[$i]->notification_sent_time =
    					is_array($rolesInfo['notification_sent_time']) ?
    					 $rolesInfo['notification_sent_time'][$i] :
    					 $rolesInfo['notification_sent_time'];
    			}
    		    if (array_key_exists('notification_confirmed_time',$rolesInfo))
    			{
    				$shift->Roles[$i]->notification_sent_time =
    					is_array($rolesInfo['notification_confirmed_time']) ?
    					 $rolesInfo['notification_confirmed_time'][$i] :
    					 $rolesInfo['notification_confirmed_time'];
    			}    			
    		}
    	}
    	return $this->subject->save($shift);
    }
    
    private function _getAndSaveMember()
    {
     	$data = array(
	    	'first_name'	=> 'Generated Test Person',
	    	'last_name' 	=> 'McGenerated',
	    	'address'		=> 'Generated address',
    		'zip_code'		=> 9090,
    		'email'			=> $this->_rand_str(200) . '@test.com', 
			'phone'			=> '92929292',
			'phonetype'    	=> 1 //TODO: type cant be statically one
    	);    	
     	$member = new Core_Model_Member();
     	$member->fromArray($data);
     	$member->save();
     	return $member;
    }
    
    private function _getAndSaveEvent()
    {
		 $data = array(
		    'name' => 'Test name',
		    'description' => 'test description',
		    'location' => 'Test',
		    'contact_name' => 'Test contact',
		    'contact_phone' => '999999999',
		    'from_date' => '2010-01-01 00:00:00',
		    'to_date' 	=> '2014-01-01 00:00:00',
		    'requested_resource' => 'requested_resource',
		    'is_active' => true,
		    'member_id' => '1',
		    'created_at' => '2010-03-11 12:37:10',
		 );    	
    	$event = new Core_Model_Event();
    	$event->fromArray($data);
    	$event->save();
    	return $event;
    }

	// Generate a random character string
	private function _rand_str($length = 32, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
	{
	    // Length of character list
	    $chars_length = (strlen($chars) - 1);
	
	    // Start our string
	    $string = $chars{rand(0, $chars_length)};
	   
	    // Generate random string
	    for ($i = 1; $i < $length; $i = strlen($string))
	    {
	        // Grab a random character from our list
	        $r = $chars{rand(0, $chars_length)};
	       
	        // Make sure the same two characters don't appear next to each other
	        if ($r != $string{$i - 1}) $string .=  $r;
	    }
	   
	    // Return the string
	    return $string;
	}
*/
}